//
//  GroupScanViewController.m
//  FZAH
//
//  Created by Yoga on 2017/4/6.
//  Copyright © 2017年 zdqk. All rights reserved.
//

#import "GroupScanViewController.h"
#import "ScanView.h"
#import "GoodDetailViewController.h"

static const char *kScanQRCodeQueueName = "ScanQRCodeQueue";

@interface GroupScanViewController () <AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic) AVCaptureSession *captureSession;
@property (nonatomic) AVCaptureVideoPreviewLayer *videoPreviewLayer;

@property (nonatomic, strong) ScanView *scanView;
@property (nonatomic) BOOL lastResut;

@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UILabel *titleLabel;
@end

@implementation GroupScanViewController

#pragma mark - CircleLife
- (void)dealloc {
    [self stopScan];
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _captureSession = [[AVCaptureSession alloc] init];
        _scanView = [[ScanView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _scanView.backgroundColor = [UIColor clearColor];
        _lastResut = YES;
        
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"扫一扫";
 //   [self showBackButton];
    [self.view addSubview:self.backButton];
    [self.view addSubview:self.titleLabel];
    [self.view insertSubview:self.scanView atIndex:0];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusDenied) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"相机使用" message:@"此功能需要开启您的相机,请您去系统设置->隐私->相机进行设置" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
        
    } else if (self.captureSession.inputs.count == 0) {
        [self setUpCamera];
    } else {
        [self startScan];
    }

    self.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [self setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.backButton.frame = CGRectMake(15, 20, 44, 44);
    
    self.titleLabel.frame = CGRectMake(self.backButton.right, 20, ScreenWidth - 2 * self.backButton.right, 44);
}

#pragma mark - method
- (void)setUpCamera {
    if ([self.captureSession canSetSessionPreset:AVCaptureSessionPresetHigh]) {
        self.captureSession.sessionPreset = AVCaptureSessionPresetHigh;
    }
    
    NSError * error;
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return;
    }
    
    [self.captureSession addInput:input];

    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    if ([self.captureSession canAddOutput:captureMetadataOutput]) {
        [self.captureSession addOutput:captureMetadataOutput];
        
        
        dispatch_queue_t dispatchQueue;
        dispatchQueue = dispatch_queue_create(kScanQRCodeQueueName, NULL);
        [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
        
        [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil]];
        
        
    }
    
    if (!_videoPreviewLayer) {
        
        _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
        [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        [_videoPreviewLayer setFrame:[UIScreen mainScreen].bounds];
        [self.view.layer insertSublayer:_videoPreviewLayer atIndex:0];

    }
    
    CGPoint origin = CGPointMake(self.scanView.width * 0.5 - self.scanView.scanSize.width * 0.5, self.scanView.height * 0.5 - self.scanView.scanSize.height * 0.5);
    CGRect captureFrame = CGRectMake(origin.x, origin.y, self.scanView.scanSize.width, self.scanView.scanSize.height);
    CGRect interRect = CGRectMake(captureFrame.origin.y / ScreenHeight, captureFrame.origin.x / ScreenWidth, captureFrame.size.height / ScreenHeight, captureFrame.size.width / ScreenWidth);
    
    captureMetadataOutput.rectOfInterest = interRect;
    
    [self startScan];

}

- (void)reportScanResult:(NSString *)result
{
    [self stopScan];
    if (!_lastResut) {
        return;
    }

    self.lastResut = NO;
    __weak typeof(self) weakSelf = self;
//    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        self.lastResut = YES;
//        [weakSelf startScan];
//    }];
    
    GoodDetailViewController *detailVC = [[GoodDetailViewController alloc] init];
    detailVC.gbarcode = result;
    [self.navigationController pushViewController:detailVC animated:YES];
    
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"二维码扫描" message:result preferredStyle:UIAlertControllerStyleAlert];
//    [alertController addAction:cancel];
//    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)startScan {
    [self.scanView startAnimation];
    if (self.captureSession.isRunning) {
        return;
    }
    [self.captureSession startRunning];
}

- (void)stopScan {
    [self.scanView stopAnimation];
    [self.captureSession stopRunning];
}

#pragma AVCaptureMetadataOutputObjectsDelegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        NSString *result;
        
        if ([[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil] containsObject:[metadataObj type]]) {
            result = metadataObj.stringValue;
        } else {
            NSLog(@"不是码");
        }
        [self performSelectorOnMainThread:@selector(reportScanResult:) withObject:result waitUntilDone:NO];
    }
}

- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[UIImage imageNamed:@"left-wh"] forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_backButton clipsToBounds];
    }
    return _backButton;
}

- (void)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Getters
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.text = @"扫一扫";
    }
    return _titleLabel;
}

@end
